package com.feifan.monthhelper.ui.guide;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.StringUtils;
import com.feifan.monthhelper.R;
import com.feifan.monthhelper.bean.db.DayRecordBean;
import com.feifan.monthhelper.bean.db.MenstrualRecordBean;
import com.feifan.monthhelper.calculate.CalculateUtils;
import com.feifan.monthhelper.calendar.CalendarUtils;
import com.feifan.monthhelper.constant.Constant;
import com.feifan.monthhelper.db.DBUtls;
import com.feifan.monthhelper.ui.MainActivity;
import com.feifan.monthhelper.ui.base.BaseActivity;
import com.feifan.monthhelper.utils.DateUtils;
import com.feifan.monthhelper.utils.NumberUtils;
import com.feifan.monthhelper.utils.SPUtils;
import com.feifan.monthhelper.wedget.DoubleClickListener;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class Step4Activity extends BaseActivity {

    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.tv_menses_date_cycle)
    TextView tvMensesDateCycle;
    @BindView(R.id.tv_birthday)
    TextView tvBirthday;
    @BindView(R.id.tv_next)
    TextView tvNext;

    TimePickerView pvTime;

    //开始时间回调函数
    OnTimeSelectListener startOnTimeSelectListener = new OnTimeSelectListener() {
        @Override
        public void onTimeSelect(Date date, View v) {
            String dataString = DateUtils.init().dateToString(date, DateUtils.DateStyle.YYYY_MM_DD);
            tvBirthday.setText(dataString);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View getTitleView() {
        return rlTitle;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView() {
        tvBirthday.setText(SPUtils.getInstance().getString(Constant.ShareKey.BIRTHDAY));

        tvBirthday.setOnClickListener(new DoubleClickListener() {
            @Override
            public void doOnClick(View view) {
                showDateSelectDialog(tvBirthday.getText().toString().trim(), Step4Activity.this, startOnTimeSelectListener);

            }
        });
        tvNext.setOnClickListener(new DoubleClickListener() {
            @Override
            public void doOnClick(View view) {
                String birthday = tvBirthday.getText().toString().trim();
                if (StringUtils.isEmpty(birthday)) {
                    return;
                }
                SPUtils.getInstance().put(Constant.ShareKey.BIRTHDAY, birthday);

                //插入数据库
                insertCalculateData();
            }
        });
    }

    private void insertCalculateData() {
        Disposable disposable = Observable.create(emitter -> {
            emitter.onNext(1);
            emitter.onComplete();
        })
                .doOnSubscribe(d -> showLoadingDialog("初始化数据..."))
                .doOnNext(o -> {
                    CalculateUtils.calculateAndSaveToDb();
                    insertMenstrual();
                })
                .doOnError(o -> dismisDialog())
                .doOnComplete(() -> dismisDialog())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(o -> startActivity(new Intent(Step4Activity.this, MainActivity.class)));
        addDisposable(disposable);
    }

    /**
     * 插入第一次经期记录
     */
    private void insertMenstrual() {
        String menstrual_start = SPUtils.getInstance().getString(Constant.ShareKey.MENSTRUAL_CYCLE_START_DATE);
        String menstrual_end = SPUtils.getInstance().getString(Constant.ShareKey.MENSTRUAL_CYCLE_END_DATE);
        MenstrualRecordBean menstrualRecordBean = new MenstrualRecordBean();
        menstrualRecordBean.start_date = DateUtils.init().StringToDate(menstrual_start, DateUtils.DateStyle.YYYY_MM_DD);
        menstrualRecordBean.end_date = DateUtils.init().StringToDate(menstrual_end, DateUtils.DateStyle.YYYY_MM_DD);
        DBUtls.insertMenstrualRecord(menstrualRecordBean);

        //插入日记录，全部为设定的经期记录
        List<DayRecordBean> dayRecordBeans = new ArrayList<>();
        int size = CalculateUtils.getDateSpan(menstrualRecordBean.end_date, menstrualRecordBean.start_date) + 1;
        for (int i=0;i<size;i++) {
            DayRecordBean recordBean = new DayRecordBean();
            recordBean.createDate = CalculateUtils.addDate(menstrualRecordBean.start_date, i);
            recordBean.state = Constant.MenstrualState.MENSTRUAL_DAY;
            dayRecordBeans.add(recordBean);
        }
        DBUtls.insertDayRecords(dayRecordBeans);
    }

//    private void calculateAndSaveToDb() {
//        String menstrual = SPUtils.getInstance().getString(Constant.ShareKey.MENSTRUAL_CYCLE_START_DATE);
//        String menstrual_cycle = SPUtils.getInstance().getString(Constant.ShareKey.MENSTRUAL_CYCLE_DAYS);
//        String menstrual_span = SPUtils.getInstance().getString(Constant.ShareKey.MENSTRUAL_CYCLE_SPAN_DAYS);
//        int menstrual_period = NumberUtils.StringToInt(menstrual_cycle.replaceAll("天", ""));
//        int span_period = NumberUtils.StringToInt(menstrual_span.replaceAll("天", ""));
//        CalculateUtils.calculateAndInsertToDb(DateUtils.init().StringToDate(menstrual, DateUtils.DateStyle.YYYY_MM_DD), menstrual_period, span_period);
//    }

    private void showDateSelectDialog(String dateString, AppCompatActivity activity, OnTimeSelectListener onTimeSelectListener) {
//        String dateString = "";
        Calendar selectedDate = CalendarUtils.getCalendarFrom(dateString);

        pvTime = new TimePickerBuilder(activity, onTimeSelectListener)
                .setType(new boolean[]{true, true, true, false, false, false})//分别对应年月日时分秒，默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentTextSize(18)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setLabel("年", "月", "日", "时", "分", "秒")
                .isDialog(false)//是否显示为对话框样式
                .build();
        pvTime.show();
    }

    @Override
    protected int setContentLayout() {
        return R.layout.activity_step4;
    }
}
